package server

import (
	"fmt"
	"github.com/hyperway/pkg/component"
	"github.com/hyperway/pkg/config"
	"github.com/hyperway/pkg/constant"
	"github.com/hyperway/pkg/impl/adapter"
	"github.com/hyperway/pkg/impl/discovery"
	"github.com/hyperway/pkg/impl/filter"
	"github.com/hyperway/pkg/logger"
	"github.com/hyperway/pkg/transporter/dubbot"
	"github.com/hyperway/pkg/transporter/httpt"
)

func Run() error {
	fmt.Printf(constant.Banner)

	initComponent()

	pool := component.NewServerPool()
	pool.NewServer(config.GetWrapper("listeners.gateway"), adapter.NewWebListener, adapter.NewWriter())
	pool.NewServer(config.GetWrapper("listeners.admin"), adapter.NewWebListener, adapter.NewWriter())
	discover := discovery.NewMockDiscover()
	pool.SetDiscover(discover)

	pool.StartGraceful()

	return nil
}

func initComponent() {
	initLifecycle()
	initFilter()
	initPreFilter()
}

// 初始化生命周期
func initLifecycle() {
	logLifecycle := logger.NewLogLifecycle()
	RegisterLifecycle(logLifecycle)

	pprofLifecycle := component.NewPprofLifecycle()
	RegisterLifecycle(pprofLifecycle)

	apolloLifecycle := config.NewApolloLifecycle()
	RegisterLifecycle(apolloLifecycle)

	go2skyLifecycle := filter.NewGo2SkyLifecycle()
	RegisterLifecycle(go2skyLifecycle)

	dubboLifecycle := dubbot.NewDubboTransporterLifecycle()
	RegisterLifecycle(dubboLifecycle)

	httpLifecycle := httpt.NewHttpTransporterLifecycle()
	RegisterLifecycle(httpLifecycle)
}

func initFilter() {
	RegisterFilter(filter.NewHystrixFilter(filter.HystrixConfig{}))
	RegisterFilter(filter.NewDubboConsumerTestFilter())
}

// 初始化前置过滤器
func initPreFilter() {
	RegisterPreFilter(filter.NewGo2SkyFilter())
}
